﻿using System.Text.RegularExpressions;
using System.Text;
using SqlSugar;

namespace Jst.Infrastructure.DbFirst
{
    /// <summary>
    /// SqlSugar DbFirst 反向工程扩展
    /// </summary>
    public static class SqlSugarDbFirstExtensions
    {
        public static void RunScaffold(ScaffoldOptions options)
        {
            options.EnsureValid();

            var db = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = options.ConnectionString,
                DbType = DbType.SqlServer, // 按需改
                IsAutoCloseConnection = true
            });

            // 1. 先拿到所有表名
            var allTables = db.DbMaintenance.GetTableInfoList()
                                 .Select(t => t.Name)
                                 .ToList();

            // 2. 按正则过滤
            var filtered = allTables
                .Where(t =>
                {
                    if (!string.IsNullOrEmpty(options.IncludeTableRegex) &&
                        !Regex.IsMatch(t, options.IncludeTableRegex))
                        return false;

                    if (!string.IsNullOrEmpty(options.ExcludeTableRegex) &&
                        Regex.IsMatch(t, options.ExcludeTableRegex))
                        return false;

                    return true;
                })
                .ToArray();

            // 3. 构造 DbFirst
            var df = db.DbFirst
                       .IsCreateAttribute()
                       .StringNullable()
                       .Where(filtered)   // 官方 API，直接传表名数组
                       .SettingClassTemplate(old =>
                       {
                           var sb = new StringBuilder(old);
                           sb.Replace("[AggregateRoot]", "")
                             .Replace("[AggregateRootAttribute]", "")
                             .Replace("AggregateRootAttribute", "");
                           return sb.ToString();
                       });

            df.CreateClassFile(options.OutputPath, options.NameSpace);
        }
    }
}

